package com.z.common.pro.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.z.common.web.vo.response.Result;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("process/forms")
public class FormController {

    @Autowired
    private TaskService taskService;

    private final String prefix = "system/process/form/";

    /**
     * 流程发起页面
     * @param processId
     * @param model
     * @return
     */
    @GetMapping("/{processId}")
    public String getForm(@PathVariable String processId, Model model) {

        String url = "/kq/leave/proEdit?processId=" + processId;
        model.addAttribute("url", url);
        model.addAttribute("id", "/kq/process/viewBpmn?id=" + processId);
        return prefix + "form";
    }
    /**
     * 流程审批页面
     * @param taskId
     * @param model
     * @return
     */
    @GetMapping("/audit/{taskId}")
    public String auditForm(@PathVariable String taskId, Model model) {
        Task task = taskService.createTaskQuery().taskId(taskId).initializeFormKeys().singleResult();
        // String formKey = task.getFormKey();
        String id = task.getProcessInstanceId();
        String url = "/kq/leave/proAudit?taskId=" + taskId;
        model.addAttribute("url", url);
        model.addAttribute("id", "/kq/process/viewBpmn?id=" + id);
        return prefix + "auditForm";
    }

    @PostMapping("/{instanceId}")
    @ResponseBody
    public Result submitForm(@PathVariable String instanceId, @RequestBody String params) {
        try {
            JSONObject o = JSON.parseObject(params);
            boolean flag = o.getBoolean("flag");
            Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();

            String id = task.getProcessInstanceId();
            Map<String, Object> map = new HashMap<>();
            map.put("approve_leader", flag);
            taskService.complete(task.getId(), map);
            task = taskService.createTaskQuery().processInstanceId(id).singleResult();
            if(task == null){
                return Result.success("流程结束");
            }
            taskService.setAssignee(task.getId(), "1");

        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
        return Result.success();
    }
}